<template>
	<view class="todo-container">
		<!-- 标签切换 -->
		<view class="tab-container">
			<view class="tab-item" :class="{ active: activeTab === 'approvals' }" @tap="switchTab('approvals')">
				<text>待我审批</text>
				<view class="badge" v-if="pendingTasks.length > 0">{{ pendingTasks.length }}</view>
			</view>
			<view class="tab-item" :class="{ active: activeTab === 'applications' }" @tap="switchTab('applications')">
				<text>我的申请</text>
				<view class="badge" v-if="myPendingApplications.length > 0">{{ myPendingApplications.length }}</view>
			</view>
		</view>

		<!-- 待我审批 -->
		<view class="todo-list" v-if="activeTab === 'approvals'">
			<view v-if="isLoading" class="loading-data">
				<text class="loading-text">加载中...</text>
			</view>

			<view v-else-if="pendingTasks.length === 0" class="empty-data">
				<text class="empty-text">暂无待处理任务</text>
			</view>

			<view v-else class="task-list">
				<view class="application-item" v-for="(task, index) in pendingTasks" :key="task.id"
					@tap="viewTaskDetail(task)">
					<view class="application-content">
						<view class="application-header">
							<view class="application-header-left">
								<text class="icon">{{ getApplicationIcon(task.workflow_type) }}</text>
								<text class="application-title">{{ getWorkflowTypeText(task.workflow_type) }}</text>
							</view>
							<text :class="['application-status', getStatusClass(task.status)]">
								{{ getStatusText(task.status) }}
							</text>
						</view>

						<view class="application-detail">
							<text class="application-desc">{{ task.business_data.detail }}</text>

							<view class="task-actions">
								<button class="btn btn-approve" @tap.stop="approveTask(task)">通过</button>
								<button class="btn btn-reject" @tap.stop="rejectTask(task)">拒绝</button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 我的申请 -->
		<view class="todo-list" v-if="activeTab === 'applications'">
			<view v-if="applicationsLoading" class="loading-data">
				<text class="loading-text">加载中...</text>
			</view>

			<view v-else-if="myApplications.length === 0" class="empty-data">
				<text class="empty-text">暂无申请记录</text>
			</view>

			<view v-else class="task-list">
				<view class="application-item" v-for="(item, index) in myApplications" :key="index"
					@tap="viewApplicationDetail(item)">
					<view class="application-content">
						<view class="application-header">
							<view class="application-header-left">
								<text class="icon">{{ getApplicationIcon(item.type) }}</text>
								<text class="application-title">{{ item.business_data.type_label }}</text>
							</view>
							<text :class="['application-status', getStatusClass(item.status)]">
								{{ getStatusText(item.status) }}
							</text>
						</view>

						<view class="application-detail">
							<text class="application-desc">{{ item.business_data.detail || item.business_data.reason ||
								'' }}</text>
							<text class="application-time" v-if="getApplicationTimeRange(item)">{{
								getApplicationTimeRange(item) }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 审批确认对话框 -->
		<uni-popup ref="approvalPopup" type="dialog">
			<uni-popup-dialog :type="approvalDialogType" :title="approvalDialogTitle" :content="approvalDialogContent"
				:before-close="true" @confirm="handleApprovalConfirm" @close="handleApprovalCancel"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { workflowApi } from '@/common/api'
import { isLoggedIn, getCurrentUser } from '@/common/auth'
import { updateTabBarBadge } from '@/common/notification'
import { uiUtils } from '@/common/uiUtils'

// 从uiUtils导入函数
const { getApplicationIcon, getStatusText,  getWorkflowTypeText, getStatusClass } = uiUtils

// 定义任务类型接口
interface Task {
	id: string;
	workflow_id: string;
	workflow_type: string;
	instance_id: string;
	business_id: string;
	current_level: number;
	status: string;
	applicant_name: string;
	applicant_id: number;
	business_data?: {
		detail?: string;
		content?: string;
		reason?: string;
		start_time?: string;
		end_time?: string;
		start_date?: string;
		end_date?: string;
		use_time?: string;
		return_time?: string;
		type_label?: string;
		[key: string]: any; // 其他可能的字段
	};
	approval_process: any[];
}

// 定义申请类型接口
interface Application {
	business_id: string;
	type: string;
	status: string;
	business_data: {
		type_label: string;
		detail: string;
		reason?: string;
		start_time?: string;
		end_time?: string;
		start_date?: string;
		end_date?: string;
		use_time?: string;
		return_time?: string;
	};
	created_at: string;
}

// 状态变量
const isLoading = ref(false)
const pendingTasks = ref<Task[]>([])
const currentTask = ref<Task | null>(null)
const activeTab = ref('approvals') // 默认显示待我审批的标签

// 我的申请相关状态
const myApplications = ref<Application[]>([])
const applicationsLoading = ref(false)



// 过滤出待处理的申请
const myPendingApplications = computed(() => {
	return myApplications.value.filter(item => item.status === 'pending')
})

// 审批对话框
const approvalPopup = ref<any>(null)
const approvalDialogType = ref('info')
const approvalDialogTitle = ref('')
const approvalDialogContent = ref('')
const approvalAction = ref('')

// 切换标签
const switchTab = (tab: string) => {
	activeTab.value = tab
	if (tab === 'approvals' && pendingTasks.value.length === 0) {
		loadPendingTasks()
	} else if (tab === 'applications' && myApplications.value.length === 0) {
		loadMyApplications()
	}
}

// 获取待办任务列表
const loadPendingTasks = async () => {
	if (!isLoggedIn()) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		return
	}

	isLoading.value = true
	try {
		const res = await workflowApi.getPendingApprovals({
			page: 1,
			limit: 20,
			include_details: true // 请求包含详细信息
		})

		if (res.success && res.data) {
			const items = res.data || []
			// 处理任务数据，确保详细信息可用
			pendingTasks.value = items.map((item: any) => {
				// 提取业务数据中的详细信息
				if (item.business_data) {
					return {
						...item,
						content: item.business_data.detail || item.business_data.content,
						reason: item.business_data.reason,
						time_range: formatTimeRange(item)
					}
				}
				return item
			})

			// 使用公共方法更新红点
			updateTabBarBadge(pendingTasks.value.length)
		} else {
			uni.showToast({
				title: res.message || '获取待办任务失败',
				icon: 'none'
			})
			updateTabBarBadge(0)
		}
	} catch (error) {
		console.error('获取待办任务失败:', error)
		uni.showToast({
			title: '网络错误，请稍后重试',
			icon: 'none'
		})
		updateTabBarBadge(0)
	} finally {
		isLoading.value = false
	}
}

// 加载我的申请列表
const loadMyApplications = async () => {
	if (!isLoggedIn()) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		return
	}

	applicationsLoading.value = true
	try {
		const res = await workflowApi.getMyApplications({ page: 1, limit: 20 })

		if (res.success && res.data) {
			// 对申请列表进行排序，将待处理的放在前面
			const items = res.data || []
			myApplications.value = items.sort((a: any, b: any) => {
				// 将 pending 状态的项目排在前面
				if (a.status === 'pending' && b.status !== 'pending') return -1
				if (a.status !== 'pending' && b.status === 'pending') return 1
				// 其他情况按时间倒序排列
				return 0
			})
			console.log('我的申请列表加载成功:', myApplications.value)
		} else {
			uni.showToast({
				title: res.message || '获取申请列表失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('获取我的申请列表出错:', error)
		uni.showToast({
			title: '网络错误，请稍后重试',
			icon: 'none'
		})
	} finally {
		applicationsLoading.value = false
	}
}

// 查看任务详情
const viewTaskDetail = (task: Task) => {
	// 跳转到专门的审批流程页面
	uni.navigateTo({
		url: `/pages/approval/approval-process?id=${task.id}&type=${task.workflow_type}&mode=approval`
	})
}

// 查看申请详情
const viewApplicationDetail = (item: Application) => {
	// 根据申请类型跳转到对应的详情页面
	const typeToPage: Record<string, string> = {
		'leave': '/pages/apply/leave',
		'business-trip': '/pages/business-trip/business-trip',		
		'purchase': '/pages/apply/purchase',
		'seal': '/pages/seal/seal',
		'vehicle': '/pages/vehicle/vehicle',	
		'expense-payment': '/pages/apply/expense-payment'
	}

	const targetPage = typeToPage[item.type]
	if (targetPage) {
		// 使用 uni-app 的页面跳转
		uni.navigateTo({
			url: `${targetPage}?id=${item.business_id}`,
			success: () => {
				console.log('跳转到申请详情页成功')
			},
			fail: (err: UniApp.GeneralCallbackResult) => {
				console.error('跳转失败:', err)
				uni.showToast({
					title: '页面跳转失败',
					icon: 'none'
				})
			}
		})
	} else {
		uni.showToast({
			title: '暂不支持查看该类型申请',
			icon: 'none',
			duration: 2000
		})
	}
}





// 获取申请时间范围
const getApplicationTimeRange = (item: Application): string => {
	if (!item.business_data) return ''

	const data = item.business_data

	// 处理请假申请
	if (item.type === 'leave' && data.start_time && data.end_time) {
		return `${formatDate(data.start_time)} 至 ${formatDate(data.end_time)}`
	}

	// 处理出差申请
	if (item.type === 'business-trip' && data.start_date && data.end_date) {
		return `${formatDate(data.start_date)} 至 ${formatDate(data.end_date)}`
	}

	// 处理用车申请
	if (item.type === 'vehicle' && data.use_time && data.return_time) {
		return `${formatDate(data.use_time)} 至 ${formatDate(data.return_time)}`
	}

	return ''
}

// 审批通过
const approveTask = (task: Task) => {
	currentTask.value = task
	approvalAction.value = 'approve'
	approvalDialogType.value = 'success'
	approvalDialogTitle.value = '审批通过'
	approvalDialogContent.value = `确认通过"${task.business_data?.type_label}"吗？`
	if (approvalPopup.value) {
		approvalPopup.value.open()
	}
}

// 审批拒绝
const rejectTask = (task: Task) => {
	currentTask.value = task
	approvalAction.value = 'reject'
	approvalDialogType.value = 'error'
	approvalDialogTitle.value = '审批拒绝'
	approvalDialogContent.value = `确认拒绝"${task.business_data?.type_label}"吗？`
	if (approvalPopup.value) {
		approvalPopup.value.open()
	}
}

// 确认审批操作
const handleApprovalConfirm = async () => {
	if (!currentTask.value) return

	try {
		const task = currentTask.value
		let res

		if (approvalAction.value === 'approve') {
			res = await workflowApi.approve(task.instance_id, '同意')
		} else {
			res = await workflowApi.reject(task.instance_id, '拒绝')
		}

		if (res.success) {
			uni.showToast({
				title: approvalAction.value === 'approve' ? '已通过' : '已拒绝',
				icon: 'success'
			})
			// 刷新任务列表
			loadPendingTasks()
			// 刷新我的申请列表（可能有状态变化）
			loadMyApplications()
		} else {
			uni.showToast({
				title: res.message || '操作失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('审批操作失败:', error)
		uni.showToast({
			title: '网络错误，请稍后重试',
			icon: 'none'
		})
	} finally {
		if (approvalPopup.value) {
			approvalPopup.value.close()
		}
	}
}

// 取消审批操作
const handleApprovalCancel = () => {
	currentTask.value = null
	if (approvalPopup.value) {
		approvalPopup.value.close()
	}
}

// 格式化日期
const formatDate = (dateString: string) => {
	if (!dateString) return ''

	const date = new Date(dateString)
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	const hours = String(date.getHours()).padStart(2, '0')
	const minutes = String(date.getMinutes()).padStart(2, '0')

	return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 格式化时间范围
const formatTimeRange = (task: any): string => {
	if (!task.business_data) return ''

	const data = task.business_data

	// 处理请假申请
	if (task.workflow_type === 'leave' && data.start_time && data.end_time) {
		return `${formatDate(data.start_time)} 至 ${formatDate(data.end_time)}`
	}

	// 处理出差申请
	if (task.workflow_type === 'businessTrip' && data.start_date && data.end_date) {
		return `${formatDate(data.start_date)} 至 ${formatDate(data.end_date)}`
	}

	// 处理用车申请
	if (task.workflow_type === 'vehicle' && data.use_time && data.return_time) {
		return `${formatDate(data.use_time)} 至 ${formatDate(data.return_time)}`
	}

	return ''
}

// 页面加载时执行
onLoad(() => {
	if (isLoggedIn()) {
	}
})

// 页面显示时执行
onShow(() => {
	if (isLoggedIn()) {
		loadPendingTasks()
		loadMyApplications()
	}
})
</script>

<style>
.todo-container {
	padding: 20rpx;
	background-color: #f5f6fa;
	min-height: 100vh;
}

.section-header {
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

/* Tab Navigation */
.tab-container {
	display: flex;
	justify-content: space-around;
	background-color: #fff;
	border-radius: 12rpx;
	padding: 10rpx 0;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
}

.tab-item {
	display: flex;
	align-items: center;
	gap: 10rpx;
	padding: 10rpx 20rpx;
	border-radius: 8rpx;
	font-size: 28rpx;
	color: #666;
	position: relative;
}

.tab-item.active {
	color: #2B5BA1;
	font-weight: bold;
	background-color: #e6f7ff;
}

.tab-item .badge {
	position: absolute;
	top: -10rpx;
	right: -10rpx;
	background-color: #f5222d;
	color: white;
	border-radius: 10rpx;
	padding: 4rpx 8rpx;
	font-size: 20rpx;
	font-weight: bold;
}

/* Task Lists */
.todo-list,
.task-list {
	width: 100%;
}

/* Loading and Empty States */
.loading-data,
.empty-data {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 100rpx 0;
}

.loading-text,
.empty-text {
	color: #999;
	font-size: 28rpx;
}

/* Application Item */
.application-item {
	background-color: #ffffff;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
	transition: background-color 0.2s ease;
}

.application-item:last-child {
	border-bottom: none;
}

.application-item:active {
	background-color: #f9f9f9;
}

/* Application Content Structure */
.application-content {
	display: flex;
	flex-direction: column;
	width: 100%;
}

.application-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12rpx;
}

.application-header-left {
	display: flex;
	align-items: center;
	gap: 10rpx;
}

.application-detail {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
}

/* Text Elements */
.icon {
	font-size: 36rpx;
	margin-right: 16rpx;
}

.application-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.application-desc {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 8rpx;
	line-height: 1.4;
}

.application-time {
	font-size: 24rpx;
	color: #999;
}

/* Status Indicators */
.application-status {
	flex: 0 0 auto;
	padding-left: 6rpx;
	font-weight: 500;
	font-size: 28rpx;
}

.application-status.pending {
	color: #2196f3;
}

.application-status.approved {
	color: #4caf50;
}

.application-status.rejected {
	color: #f44336;
}

/* Action Buttons */
.task-actions {
	display: flex;
	justify-content: flex-end;
	gap: 20rpx;
	margin-top: 16rpx;
	width: 100%;
}

.btn {
	padding: 2rpx 48rpx;
	border-radius: 8rpx;
	font-size: 28rpx;
	border: none;
}

.btn-approve {
	background-color: #2B5BA1;
	color: white;
}

.btn-reject {
	background-color: white;
	color: #f5222d;
	border: 1rpx solid #f5222d;
}
</style>